#include "stdafx.h"
#include "element.h"

BEGIN_ATTRIBUTE(CxElement)
    ATTRIBUTE(ID, E_ATTRI_INT, IxElement, SetID)
END_ATTRIBUTE

CxElement::CxElement()
    : m_nID(0)
{
    ATTRUBTES(CxElement)
}

CxElement::~CxElement()
{}

HRESULT CxElement::GetID(LPINT pnID)
{
    if (*pnID)  return E_POINTER;

    *pnID = m_nID;

    return S_OK;
}

HRESULT CxElement::SetID(INT nID)
{
    m_nID = nID;
    return S_OK;
}

HRESULT CxElement::AddObserver(IxEventObserver* pObserver)
{
    OBSERVERLIST::iterator it = std::find(m_ltObservers.begin(), m_ltObservers.end(), pObserver);

    if (it != m_ltObservers.end())
    {
        m_ltObservers.push_front(CComPtr<IxEventObserver>(pObserver));
        return S_OK;
    }

    return S_FALSE;
}

HRESULT CxElement::RemoveObserver(IxEventObserver* pObserver)
{
    OBSERVERLIST::iterator it = std::find(m_ltObservers.begin(), m_ltObservers.end(), pObserver);

    if (it != m_ltObservers.end())
    {
        m_ltObservers.erase(it);
        return S_OK;
    }

    return S_FALSE;
}

HRESULT CxElement::ClearObserver()
{
    m_ltObservers.clear();
    return S_OK;
}

HRESULT CxElement::RaiseEvent(INT nEventId, VOID* pData)
{
    BOOL bCallNext = TRUE;

    for (OBSERVERLIST::iterator it = m_ltObservers.begin(); it != m_ltObservers.end() && bCallNext; ++it)
    {
        CComPtr<IxEventObserver> spObserver = *it;
        if (spObserver)
        {
            spObserver->OnEvent(nEventId, m_nID, GetEntity<IUnknown>(), pData, &bCallNext);
        }
    }

    return S_OK;
}